package cn.tjad.tjad2.module.document.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.activity.BaseActivity;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.consts.TjadConsts;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.listener.OnItemLongClickListener;
import cn.tjad.tjad2.module.document.adapter.OfflineModelAdapter;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.DocumentHelper;
import cn.tjad.tjad2.utils.FileHelper;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

@Route(path = PageId.OFFLINE_LIST)
public class OfflineModelActivity extends BaseActivity implements OnItemClickListener, OnItemLongClickListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    private OfflineModelAdapter adapter;
    private int projectId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_recylerview);
        swipeRefreshLayout.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new OfflineModelAdapter(null);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemLongClickListener(this);
        recyclerView.setAdapter(adapter);
        projectId = TjadApplication.getInstance().getSession().getProjectId();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        String documentPath = TjadConsts.UNZIP_DOCUMENT;
        File documentPathFile = new File(documentPath);
        String[] childs = documentPathFile.list();
        if (childs != null) {
            adapter.updateData(Arrays.asList(childs));
            adapter.notifyDataSetChanged();
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onItemClick(View parentView, View itemView, int position) {
        String fileStr = adapter.getItemData(position);
        if (!fileStr.startsWith(TjadConsts.UNZIP_DOCUMENT)) {
            fileStr  = TjadConsts.UNZIP_DOCUMENT + "/" + fileStr;
        }
        File file = new File(fileStr);
        if (file.exists()) {
            DocumentHelper.openLocalFile(this, fileStr, 0);
//            String token = TjadApplication.getInstance().getSession().getToken();
//            String url = UrlUtils.getUrl(UrlConsts.LOCAL_DOCUMENT_PREVIEW_URL, "" + TjadHttpServer.PORT, TjadConsts.APPHTML,
//                    fileStr, token, projectId + "");
//
//
//            //localFile, String.valueOf(projectId), token, "127.0.0.1", "9578", String.valueOf(id));
//            Bundle bundle = new Bundle();
//            bundle.putString("url", url);
//            RouteUtils.toPage(this, PageId.WEBVIEW, bundle);
        }
    }

    @Override
    public boolean onItemLongClick(View parentView, View itemView, int position) {
        String fileStr = adapter.getItemData(position);
        String fileName = fileStr;
        if (!fileStr.startsWith(TjadConsts.UNZIP_DOCUMENT)) {
            fileName = fileStr;
            fileStr  = TjadConsts.UNZIP_DOCUMENT + "/" + fileStr;
        } else {
            fileName = fileStr.substring(fileStr.lastIndexOf("/") + 1);
        }
        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
        final String finalFileStr = fileStr;
        String finalFileName = fileName;
        builder.setTitle(adapter.getItemData(position))
                .setMessage("是否确认删除该离线模型？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int i) {
                        File file = new File(finalFileStr);
                        if (file.exists()) {
                            FileHelper.deleteFile(finalFileStr);
                            Tools.showToast("删除成功");
                        }
                        //删除下载文件夹中对应的zip文件
                        File downloadDir = new File(TjadConsts.DOWNLOAD_FILE);
                        if (downloadDir.exists()) {
                            File[] filterFile = downloadDir.listFiles(new FilenameFilter() {
                                @Override
                                public boolean accept(File file, String s) {
                                    return s.contains(finalFileName);
                                }
                            });
                            if (filterFile != null && filterFile.length > 0) {
                                for (File f: filterFile) {
                                    f.delete();
                                }
                            }
                        }
                        loadData();
                        return true;
                    }
                }).show(getSupportFragmentManager());
        return true;
    }

    @Override
    public void onRefresh() {
        loadData();
    }
}
